/** 
 * 压缩图片
 * @param {Object} fileSource 文件对象
 */
export function compress(fileSource) {
	return new Promise((resolve, reject) => {
		var reader = new FileReader();
		reader.readAsDataURL(fileSource); //读取图像文件 result 为 DataURL, DataURL 可直接 赋值给 img.src
		reader.onload = function (event) {
			var img = new Image();
			img.src = event.target.result; // base64
			img.onload = function () {
				// 默认按比例压缩
				var that = this;
				var h = that.height;
				var w = that.width;
				var max = h > w ? h : w
				// 超过1920的按照比例缩小
				if (max > 1920) {
					var scale = max / 1920
					h = Number((h / scale).toFixed(0))
					w = Number((w / scale).toFixed(0))
				}

				var canvas = document.createElement('canvas');
				var ctx = canvas.getContext('2d');
				var anw = document.createAttribute("width");
				anw.nodeValue = w;
				var anh = document.createAttribute("height");
				anh.nodeValue = h;
				canvas.setAttributeNode(anw);
				canvas.setAttributeNode(anh);
				ctx.drawImage(that, 0, 0, w, h);
				// 压缩比例
				var quality = 0.5;
				var base64 = canvas.toDataURL('image/jpeg', quality);
				canvas = null;
				var file = base64ToFile(base64, fileSource.name);
				resolve({
					file,
					width: w,
					height: h
				});
			}
		}
	})
}

/** 
 * base64转file对象 
 * @param {Object} base64 base64地址 
 * @param {Object} filename 文件名称
 */
export function base64ToFile(base64, filename) {
	var arr = base64.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new File([u8arr], filename, {
		type: mime
	});
}